package de.mhus.lib.mandala.demo;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import de.mhus.lib.core.MSingleton;
import de.mhus.lib.core.base.AnnotationInjectStrategy;
import de.mhus.lib.core.base.BaseByThreadStrategy;
import de.mhus.lib.core.lang.BaseControl;
import de.mhus.lib.mandala.Response;
import de.mhus.lib.mandala.Ui;
import de.mhus.lib.mandala.UiControl;
import de.mhus.lib.mandala.Window;
import de.mhus.lib.mandala.servlet.MandalaServlet;

public abstract class Demo {

	public Window createWindow(HttpServletRequest request) {
		
		BaseControl bc = MSingleton.get().getBaseControl();
		
		if (!(bc.getFindStrategy() instanceof BaseByThreadStrategy))
			bc.setFindStrategy(new BaseByThreadStrategy());
		
		if (!(bc.getInjectStrategy() instanceof AnnotationInjectStrategy))
			bc.setInjectStrategy(new AnnotationInjectStrategy());
		
		Window window = (Window)request.getSession().getAttribute("__mandala_demo");
		
		if (request.getParameter("__mandala_reset") != null)
			window = null;
		
		if (window == null) {
			
			try {
				Ui ui = MandalaServlet.getUi(request);
				window = ui.createWindow();
				bc.base(null).addObject(Window.class, window);
	
				create(window);
				request.getSession().setAttribute("__mandala_demo", window);
				
			} finally {
				bc.base(null).removeObject(Window.class);
			}
		}
		return window;
	}

	protected abstract void create(Window window);
	
	
	public Window render(HttpServletRequest request, HttpServletResponse response ) throws IOException {
		Window window = createWindow(request);
		
		Response r = window.getUi().createResponse(window, request, response);
		
		window.doRender(null, r);
		
		return window;
	}
	
}
